class AiChatMessage {
  final int? id;
  final String role; // 'user' 或 'assistant'
  final String content;
  final int createdAt;

  AiChatMessage({
    this.id,
    required this.role,
    required this.content,
    required this.createdAt,
  });

  // 从Map创建AiChatMessage对象
  factory AiChatMessage.fromMap(Map<String, dynamic> map) {
    return AiChatMessage(
      id: map['id']?.toInt(),
      role: map['role'] ?? 'user',
      content: map['content'] ?? '',
      createdAt: map['created_at']?.toInt() ?? DateTime.now().millisecondsSinceEpoch,
    );
  }

  // 转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'role': role,
      'content': content,
      'created_at': createdAt,
    };
  }

  // 复制并修改
  AiChatMessage copyWith({
    int? id,
    String? role,
    String? content,
    int? createdAt,
  }) {
    return AiChatMessage(
      id: id ?? this.id,
      role: role ?? this.role,
      content: content ?? this.content,
      createdAt: createdAt ?? this.createdAt,
    );
  }

  @override
  String toString() {
    return 'AiChatMessage{id: $id, role: $role, content: ${content.length > 50 ? content.substring(0, 50) + "..." : content}}';
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is AiChatMessage && other.id == id;
  }

  @override
  int get hashCode => id.hashCode;
}